function jsonToTree(json) {
    let result = []
    if (!Array.isArray(json)) {
        return result
    }
    const map = {}
    // 创建节点映射表（id -> 节点）
    json.forEach(item => {
        map[item.id] = item
    })
    json.forEach(item => {
        const parent = map[item.pid]
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(map[item.id])
        }
    })
    return result
}

let source = [{
    id: 1,
    pid: 0,
    name: 'body'
}, {
    id: 2,
    pid: 1,
    name: 'title'
}, {
    id: 3,
    pid: 2,
    name: 'div'
}]

console.log(jsonToTree(source))